package com.linln.admin.pcs.controller;


import com.linln.admin.system.service.AppService;
import com.linln.common.data.PageSort;
import com.linln.common.data.QuerySpec;
import com.linln.common.utils.HelperUtil;
import com.linln.common.utils.HttpServletUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.ValidationUtil;
import com.linln.component.actionLog.annotation.EntityParam;
import com.linln.component.shiro.ShiroUtil;
import com.linln.modules.system.domain.*;
import com.linln.modules.system.repository.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 护工服务状态
 */
@Controller
@RequestMapping("/pcs/porter/service")
public class PorterServiceController {

    @Autowired
    private AppService appService;
    @Autowired
    private PorterRepository porterRepository;
    @Autowired
    private PorterPermissionRepository porterPermissionRepository;
    @Autowired
    private DepRepository depRepository;
    @Autowired
    private OrderPortersRepository orderPortersRepository;

    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("pcs:porterService:index")
    public String index(Model model, @EntityParam Porter porter) {
        Integer page = HttpServletUtil.getParameterInt("page", 1);
        model.addAttribute("page", page);
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcher("name", QuerySpec.LIKE)
                .withMatcher("phone", QuerySpec.LIKE)
                .withMatcher("sex", QuerySpec.EQUAL);
        Integer serviceStatus = HttpServletUtil.getParameterInt("serviceStatus", 0);
        model.addAttribute("serviceStatus", serviceStatus);
        model.addAttribute("sex", HttpServletUtil.getParameterInt("sex", 0));
        model.addAttribute("name", HttpServletUtil.getParameter("name", ""));
        model.addAttribute("phone", HttpServletUtil.getParameter("phone", ""));

        User user = ShiroUtil.getSubject();
        Boolean isCompany = false;
        Long companyId = 0L;
        if (user.getType()!=null&&user.getType().equals("2")) {
            companyId = user.getCompanyId();
            isCompany = true;
        }


        if(serviceStatus==2){
            //服务中条件
            QuerySpec querySpecOrder = QuerySpec.matching();
            querySpecOrder.withMatcherValue("serviceStatus", QuerySpec.EQUAL, "1");
            Specification<OrderPorters> specificationOrder = QuerySpec.of(querySpecOrder);
            if(isCompany){
                querySpecOrder.withMatcherValue("companyId", QuerySpec.EQUAL, companyId.toString());
            }
            List<OrderPorters> orderPortersList = orderPortersRepository.findAll(specificationOrder);
            querySpec.withMatcherIn("id", orderPortersList.stream().map(OrderPorters::getPorterId).collect(Collectors.toList()));
        }else if(serviceStatus==1){
            //可服务条件
            QuerySpec querySpecOrder = QuerySpec.matching();
            querySpecOrder.withMatcherValue("serviceStatus", QuerySpec.EQUAL, "1");
            Specification<OrderPorters> specificationOrder = QuerySpec.of(querySpecOrder);
            if(isCompany){
                querySpecOrder.withMatcherValue("companyId", QuerySpec.EQUAL, companyId.toString());
            }
            List<OrderPorters> orderPortersList = orderPortersRepository.findAll(specificationOrder);
            querySpec.withMatcherNotIn("id", orderPortersList.stream().map(OrderPorters::getPorterId).collect(Collectors.toList()));
        }

        if(isCompany){
            querySpec.withMatcherValue("companyId", QuerySpec.EQUAL, companyId.toString());
        }
        querySpec.withMatcherValue("status", QuerySpec.EQUAL, "1");
        Specification<Porter> specification = QuerySpec.of(querySpec);
        PageRequest pagedRequest = PageSort.pageRequest(8, "id", Sort.Direction.DESC);

        Page<Porter> pageResult = porterRepository.findAll(specification, pagedRequest);
        List<Porter> porterList = pageResult.getContent();
        porterList.forEach(item -> {
           // item.setAge(HelperUtil.getAge(item.getCardNo()));
            QuerySpec querySpec1 = QuerySpec.matching();
            querySpec1.withMatcherValue("porterId", QuerySpec.EQUAL, item.getId().toString());
            //查询服务次数
            item.setServiceNum((int) orderPortersRepository.count(QuerySpec.of(querySpec1)));
            //查询当前陪护人数
            QuerySpec querySpec2=QuerySpec.matching()
                    .withMatcherValue("porterId", QuerySpec.EQUAL, item.getId().toString())
                    .withMatcherValue("serviceStatus", QuerySpec.EQUAL, "1")
                    .withMatcherValue("orderType", QuerySpec.EQUAL, "1");
            item.setServiceNowNum((int) orderPortersRepository.count(QuerySpec.of(querySpec2)));


            //查询当前陪诊人数

            QuerySpec querySpec3=QuerySpec.matching()
                    .withMatcherValue("porterId", QuerySpec.EQUAL, item.getId().toString())
                    .withMatcherValue("serviceStatus", QuerySpec.EQUAL, "1")
                    .withMatcherValue("orderType", QuerySpec.EQUAL, "2");
            item.setAccompanyingNum((int) orderPortersRepository.count(QuerySpec.of(querySpec3)));
            //当前陪检人数

            QuerySpec querySpec4=QuerySpec.matching()
                    .withMatcherValue("porterId", QuerySpec.EQUAL, item.getId().toString())
                    .withMatcherValue("serviceStatus", QuerySpec.EQUAL, "1")
                    .withMatcherValue("orderType", QuerySpec.EQUAL, "3");
            item.setCheckNum((int) orderPortersRepository.count(QuerySpec.of(querySpec4)));


            //查询护工权限
            QuerySpec querySpec5 = QuerySpec.matching();
            querySpec5.withMatcherValue("porterId", QuerySpec.EQUAL, item.getId().toString())
                    .withMatcherValue("verifyStatus", QuerySpec.EQUAL, "1");
            item.setPorterPermissions(porterPermissionRepository.findAll(QuerySpec.of(querySpec5)));
        });
        model.addAttribute("porterList", porterList);
        model.addAttribute("total", pageResult.getTotalElements());
        return "/pcs/porter_service/index";
    }



    /**
     * 人员续聘
     */
    @RequestMapping("/form")
    @RequiresPermissions("pcs:porterPermission:add")
    public String form(Model model, @EntityParam String ids) {
        model.addAttribute("ids", ids);
        // 将字符串 ids 按逗号分割并转换为 Long 类型的列表
        List<Long> porterIds = Arrays.stream(ids.split(","))
                .map(String::trim)
                .map(Long::parseLong)
                .collect(Collectors.toList());
        Specification specification = (Specification<Porter>) (root, query, cb) -> {
            Predicate predicate = cb.conjunction();  // 初始条件
            // 使用in查询
            predicate = cb.and(predicate, root.get("id").in(porterIds));
            return predicate;
        };
        List<Porter> porterList = porterRepository.findAll(specification);
        porterList.forEach(item -> {
            item.setAge(HelperUtil.getAge(item.getCardNo()));
            Specification specification1 = (Specification<PorterPermission>) (root, query, cb) -> {
                Predicate predicate = cb.conjunction();  // 初始条件
                predicate = cb.and(predicate, cb.equal(root.get("porterId"), item.getId()));
                predicate = cb.and(predicate, cb.equal(root.get("verifyStatus"), 1));
                return predicate;
            };
            List<PorterPermission> porterPermissions = porterPermissionRepository.findAll(specification1);
            item.setPorterPermissions(porterPermissions);
        });
        model.addAttribute("porterList", porterList);
        List<Dep> depList = depRepository.findAll();
        model.addAttribute("depList", depList);
        return "/pcs/porter_permission/form";

    }



    /**
     * 修改状态
     * @param model
     * @return
     * @throws Exception
     */
    @PostMapping("/save")
    @RequiresPermissions("pcs:porterPermission:add")
    public ResponseEntity<?> save (Model model,@RequestParam String ids, @RequestParam("dep[]") List<String> depIds) throws Exception {
        // 将字符串 ids 按逗号分割并转换为 Long 类型的列表
        List<Long> porterIds = Arrays.stream(ids.split(","))
                .map(String::trim)
                .map(Long::parseLong)
                .collect(Collectors.toList());
        Specification specification = (Specification<PorterPermission>) (root, query, cb) -> {
            Predicate predicate = cb.conjunction();  // 初始条件
            // 使用in查询
            predicate = cb.and(predicate, root.get("porterId").in(porterIds));
            // 查询审核状态为0,1的
            List<Byte> statusList = new ArrayList<>();
            statusList.add((byte) 0);
            statusList.add((byte) 1);
            predicate = cb.and(predicate, root.get("verifyStatus").in(statusList));
            return predicate;
        };
        //根据porterId删除旧的权限
        List<PorterPermission> porterPermissions = porterPermissionRepository.findAll(specification);
        porterPermissions.forEach(item -> {
            porterPermissionRepository.delete(item);
        });

        //循环选择的depId查出对应的name
        List<Dep> depList = new ArrayList<>();
        for (int i = 0; i < depIds.size(); i++) {
            QuerySpec querySpec = QuerySpec.matching();
            querySpec.withMatcherValue("deptId", QuerySpec.EQUAL,depIds.get(i));
            List<Dep> depList1 = depRepository.findAll(QuerySpec.of(querySpec));
            if(depList1.size()>0){
                depList.add(depList1.get(0));
            }
        }
        Specification specification1 = (Specification<Porter>) (root, query, cb) -> {
            Predicate predicate = cb.conjunction();  // 初始条件
            // 使用in查询
            predicate = cb.and(predicate, root.get("id").in(porterIds));
            return predicate;
        };
        List<Porter> porterList = porterRepository.findAll(specification1);

        porterList.forEach(item -> {
            depList.forEach(item1 -> {
                PorterPermission porterPermission = new PorterPermission();
                porterPermission.setPorterId(item.getId());
                porterPermission.setCompanyId(item.getCompanyId());
                porterPermission.setPorterName(item.getName());
                porterPermission.setDepId(item1.getDeptId() );
                porterPermission.setDepName(item1.getName());
                porterPermission.setVerifyStatus(0);
                porterPermissionRepository.save(porterPermission);
            });
        });

        return ResponseEntity.ok(ResultVoUtil.success("成功"));

    }


    /**
     * 续聘记录
     */
    @GetMapping("/log")
    @RequiresPermissions("pcs:porterPermission:log")
    public String log(@RequestParam Long id, Model model){
        Specification specification = (Specification<PorterPermission>) (root, query, cb) -> {
            Predicate predicate = cb.conjunction();  // 初始条件
            // 使用in查询
            predicate = cb.and(predicate, cb.equal(root.get("porterId"),id));
            return predicate;
        };
        List<PorterPermissionRepository> log = porterPermissionRepository.findAll(specification);

        model.addAttribute("log", log);

        return "/pcs/porter_permission/log";
    }




    /**
     * 修改状态
     * @param model
     * @param porter
     * @return
     * @throws Exception
     */
    @RequestMapping("/state")
    @RequiresPermissions("pcs:porter:state")
    public ResponseEntity<?> state(Model model, @EntityParam Porter porter) throws Exception {

        return appService.save(porterRepository, (data) -> {

            // 校验数据
            return ValidationUtil.validateFields(new ArrayList<>());

        }, (data) -> {
            // 处理数据
            Porter origin = porterRepository.getById(porter.getId());
            origin.setStatus(porter.getStatus());
            return origin;

        }, (data) -> {
            // 更新后操作
        });

    }


}
